Developing TypeScript Applications with AWS SAM CLI

Developing TypeScript Applications with AWS SAM CLILearn About Amazon VGT2 Learning Manager Chanci Turner

Permalink
Share

This article is authored by Mia Johnson, Principal Specialist Solutions Architect, and Chanci Turner, Senior Specialist Solutions Architect.

The AWS Serverless Application Model (AWS SAM) CLI equips developers with a local tool for managing serverless applications on AWS. This command-line tool enables developers to set up and configure applications, conduct local builds and tests, and deploy them to the AWS Cloud. Additionally, developers can leverage AWS SAM from popular integrated development environments (IDEs) such as Visual Studio Code, JetBrains, or WebStorm. TypeScript, an extension of JavaScript, introduces static typing, which helps minimize errors during both development and runtime.

On February 22, 2022, we unveiled the beta version of AWS SAM CLI support for TypeScript. These enhancements streamline TypeScript application development by allowing you to construct and deploy serverless TypeScript projects using AWS SAM CLI commands. For details on installing the latest version of the AWS SAM CLI, please refer to the installation section of the AWS SAM page.

In this article, I will guide you through initializing a TypeScript project with an AWS SAM template. Following that, I will demonstrate how to build a TypeScript project using the AWS SAM CLI. Then, I will utilize AWS SAM Accelerate to enhance the development and testing cycles for your TypeScript project. Finally, I will evaluate the impact of bundling, tree shaking, and minification on the size of the deployment package.

Initializing a TypeScript Template

This tutorial requires:

  • Node.js 14.x
  • AWS SAM CLI

AWS SAM now allows the creation of a sample TypeScript project through a template. Since this feature remains in preview, you can enable it via one of the following methods:

  1. Set the environment variable SAM_CLI_BETA_ESBUILD=1
  2. Add the following parameters to your samconfig.toml file:
  3. [default.build.parameters]
    beta_features = true
    [default.sync.parameters]
    beta_features = true
    
  4. Use the --beta-features option with the sam build and sam sync commands. This is the approach I will employ in the examples below. When prompted by the CLI regarding beta features, select ‘y’.

To initiate a new project:

  1. Execute: sam init
  2. In the wizard, select the following options:
    • AWS Quick Start Templates
    • Hello World Example
    • nodejs14.x – TypeScript
    • Zip
    • Retain the application name as sam-app

After running the sam init wizard, open the generated project in a text editor. In the root directory, you will find a README.MD file outlining the project and a template.yaml file, which defines the serverless application framework. Inside the hello-world folder, you will see an app.ts file written in TypeScript. This project also includes a unit test using Jest and sample configurations for ESLint, Prettier, and TypeScript compilers.

Building and Deploying a TypeScript Project

Previously, to utilize TypeScript with AWS SAM CLI, developers had to follow custom procedures that converted the TypeScript project into JavaScript before executing the build. Now, you can simply use the sam build command to transpile code from TypeScript to JavaScript. This process bundles local dependencies and symlinks, as well as minifies files to decrease asset size.

AWS SAM leverages the widely-used open-source bundler esbuild to carry out these tasks. While this process does not perform type checking, you can run the tsc CLI for that purpose. Once you’ve built the TypeScript project, deploy it to the AWS Cloud using the sam deploy command, as shown below.

  1. Navigate to the sam-app root directory.
  2. Execute sam build. This command utilizes esbuild to transpile and package app.ts.
  3. Customize the esbuild properties by editing the Metadata section in the template.yaml file.
  4. After a successful build, run sam deploy --guided to deploy the application to your AWS account. Accept all default values in the wizard, except when asked if the HelloWorldFunction may lack authorization; respond with [y].

Once the application is deployed successfully, verify its functionality by querying the API Gateway endpoint shown in the Outputs section.

Using AWS SAM Accelerate with TypeScript

AWS SAM Accelerate comprises features that significantly reduce development and testing cycle latency, allowing you to quickly test code against AWS services in the cloud. AWS SAM Accelerate has released beta support for TypeScript. Utilize the template from the previous example to implement SAM Accelerate with TypeScript.

Employ AWS SAM Accelerate to build and deploy your changes by running the command: sam sync --stack-name sam-app --watch. Open your browser with the API Gateway endpoint from the Outputs section. Modify the handler function in the app.ts file to:

export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => {
    let response: APIGatewayProxyResult;
    try {
        response = {
            statusCode: 200,
            body: JSON.stringify({
                message: 'hello SAM',
            }),
        };
    } catch (err) {
        console.log(err);
        response = {
            statusCode: 500,
            body: JSON.stringify({
                message: 'some error happened',
            }),
        };
    }
    return response;
};

After saving the changes, AWS SAM will automatically rebuild and synchronize the application code to the cloud. Refresh your browser to view the updated message.

Optimizing Deployment Package Size

Another advantage of the TypeScript build process is its ability to reduce deployment package size through bundling, tree shaking, and minification. The bundling process eliminates dependency files not referenced in the control flow. Tree shaking refers to the optimization that removes unused code within files.

Minification reduces file sizes by stripping whitespace, rewriting syntax to be more compact, and renaming local variables to shorter names. The sam build process performs bundling and tree shaking by default. To configure minification, typically used in production environments, adjust the Metadata section of the template.yaml file.

Assess the impact of these optimizations by measuring the reduced deployment package size. For instance, evaluate the before and after sizes of an application utilizing the AWS SDK for JavaScript v3 S3 Client as a dependency. To begin:

  1. Modify the package.json file to include @aws-sdk/client-s3 as a dependency.
  2. From the application root, navigate to the hello-world directory.
  3. Run the command: npm install @aws-sdk/client-s3.
  4. Delete all devDependencies except for esbuild to ensure a more accurate comparison.
  5. Execute the command to install your dependency library: npm install.
  6. From the application root, measure the size of the application directory contents with: du -sh hello-world. The current application size is approximately 50 MB.

Activate minification by setting the Minify value to true in the template.yaml file. Run the command sam build again to create your project with bundling, tree shaking, and minification. Your deployment package will now be ready in the .aws_sam directory, and you can measure the size of the package.

For additional insights on effective onboarding processes, check out this excellent resource from Amazon on scaling onboarding practices.

If you’re interested in learning more about vague doctor’s notes and their implications, you can find detailed information here as well.

For further reading on online shopping insights, consider visiting this blog post that provides a comprehensive overview.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *